<template>
  <view>
    <view class="goods-list">
      <view v-for="item in goodsList" :key="item.goods_id" @click="gotoDetail(item)">
        <my-goods :goods='item'></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //页面参数对象
        queryObj: {
          //查询关键字
          query: '',
          //商品分类id
          cid: '',
          //页码值
          pagenum: 1,
          //每页显示数据条数
          pagesize: 10
        },
        goodsList: [], //存放商品列表数据
        total: 0, //商品总数居
        isloading:false//节流阀

      };
    },
    onLoad(options) {
      //options为页面参数
      // console.log(options);
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      //调用获取商品列表数据方法
      this.getGoodsList()
    },
    methods: {
      //请求商品列表数据
      async getGoodsList(cb) {
        try {
        this.isloading=true//打开节流阀
          const {data} = await uni.$http.get('/goods/search', this.queryObj)
          this.isloading=false//关闭节流阀
          cb&&cb()//数据请求完毕，调用关闭下拉刷新的函数
          if (data.meta.status !== 200) return uni.$showMsg()
          // console.log(data)
          this.goodsList = [...this.goodsList, ...data.message.goods]
          this.total = data.message.total
        } catch (e) {
          console.log(e);
          uni.$showMsg()
        }
      },
      //触底事件
      onReachBottom() {
        // console.log(1);
        if(this.isloading) return//判断节流阀是否打开
        //判断是否还有数据
        if (this.goodsList.length >= this.total) {
          return uni.$showMsg('暂无更多数据！')
        }
        this.queryObj.pagenum = this.queryObj.pagenum + 1
        //有数据继续请求
        this.getGoodsList()
      },
      //下拉刷新事件
      onPullDownRefresh(){
        //重置数据
        this.queryObj.pagenum=1,
        this.goodsList=[],
        this.total=0,
        this.isloading=false
        //重新发起网络请求，并关闭下拉刷新
        this.getGoodsList(()=>uni.stopPullDownRefresh())
      },
      //点击商品项，跳转到商品详情页
      gotoDetail(item){
        uni.navigateTo({
          url:'/subpkg/goods_detail/goods_detail?goods_id='+item.goods_id
        })
      }
    }
  }
</script>

<style lang="scss">

</style>
